﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using FreesenseSubAIS.Core;
using FreesenseSubAIS.UI;
using System.IO;
using Sea;

namespace FreesenseSubAIS.NewUI
{
    public partial class SetParameterControl : UserControl
    {
        ProjectParam _tempproduct;//产品型号参数
        AlgParameter _selectedpara;//图片参数
        bool _hang;
        private bool _isLoad;//ListView不需要响应Checked事件
        public SetParameterControl()
        {
            InitializeComponent();
            panel1.BringToFront();
        }
        public void LoadProduct(ProjectParam product)
        {
            _tempproduct = product;
            if (_tempproduct == null)
            {
                productn_tx.ReadOnly = false;
                _tempproduct = new ProjectParam("");
                _tempproduct.ParamList = new List<AlgParameter>();
            }
            productn_tx.Text = _tempproduct.ProductName;
            picturelist_Rad.Items.Clear();
            foreach (var pro in _tempproduct.ParamList)
            {
                picturelist_Rad.Items.Add(pro.PicParameter.Picname);
            }
            propertyGrid2.SelectedObject = _tempproduct;
            propertyGrid2.ExpandAllGridItems();
            LoadTypeConfig();
            if (picturelist_Rad.Items.Count > 0)
                picturelist_Rad.SelectedIndex = 0;
            comboBox1.SelectedIndex = 1;
        }
        public void LoadTypeConfig()
        {
            try
            {
                _isLoad = true;
                listView1.Items.Clear();
                foreach (int myCode in Enum.GetValues(typeof(SelectedFuction)))
                {
                    string strName = Enum.GetName(typeof(SelectedFuction), myCode);//获取名称
                    var strVaule = myCode;//获取值
                    listView1.Items.Add(string.Format("{0}-{1}", strVaule, strName), strVaule);
                }
                _isLoad = false;
                comboBox1.Items.Clear();
                foreach (int myCode in Enum.GetValues(typeof(ParamRank)))
                {
                    string strName = Enum.GetName(typeof(ParamRank), myCode);//获取名称
                    var strVaule = myCode;//获取值
                    comboBox1.Items.Add(string.Format("{0}-{1}", strVaule, strName));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("算法配置文件“calcDescribe.des”加载失败{0}异常:{1}", Environment.NewLine, ex.Message), "警告", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            Rerefrush(2 * (comboBox1.SelectedIndex + 1), tabControl2.SelectedIndex);
            panel1.Visible = comboBox1.SelectedIndex > 0;
        }
        /// <summary>
        /// 分权限显示参数
        /// </summary>
        /// <param name="grade">权限等级</param>
        private void Rerefrush(int grade, int index)
        {
            try
            {
                if (grade < 0 || _selectedpara == null)
                    return;
                Type ct = _selectedpara.InspGroup[index].Sp.GetType();
                var typelist = new List<int>(_selectedpara.InspGroup[index].InspMethods);
                var namelist = new List<string>();
                foreach (var method in typelist)
                {
                    var list = new List<string>();
                    (new InspParameter()).getFunctionParam(method, list);
                    namelist.AddRange(list);
                }
                ChangeProperty.ChangePropertyVisibility(_selectedpara.InspGroup[index].Sp, ct, grade, namelist);
                if (tabControl2.TabPages[index] is IRefresh)
                    (tabControl2.TabPages[index] as IRefresh).RefreshProperty();
            }
            catch (Exception ex)
            {
                MessageBox.Show("操作失败!\n" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        private void picturelist_Rad_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e)
        {
            try
            {
                if (_tempproduct.ParamList == null || _tempproduct.ParamList.Count < 1)
                    return;
                if (picturelist_Rad.Items.Count > 0 && picturelist_Rad.SelectedIndex > -1 && picturelist_Rad.SelectedIndex < _tempproduct.ParamList.Count)
                {
                    int index = picturelist_Rad.SelectedIndex;
                    _selectedpara = new AlgParameter();
                    _selectedpara = _tempproduct.ParamList[index];
                    picname_tx.Text = _selectedpara.PicParameter.Picname;
                    tabControl2.TabPages.Clear();
                    foreach (var group in _selectedpara.InspGroup)
                    {
                        var ptp = new ParamTabelPage();
                        ptp.SetSourcce(group);
                        tabControl2.TabPages.Add(ptp);
                    }
                    SelectMethod(_selectedpara.InspGroup.FirstOrDefault());
                    propertyGrid1.SelectedObject = _selectedpara.PicParameter;
                    propertyGrid1.ExpandAllGridItems();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("图片参数打开失败！" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void SelectMethod(InspGroupParameter param)
        {
            var sel = param == null ? new List<int>() : param.InspMethods;
            _isLoad = true;
            foreach (var s in listView1.Items)
                (s as ListViewItem).Checked = false;
            _isLoad = false;
            if (listView1.Items.Count > 0 && sel != null && sel.Count > 0)
            {
                for (int i = 0; i < listView1.Items.Count; i++)
                {
                    var items = listView1.Items[i] as ListViewItem;
                    if (sel.Contains(items.ImageIndex))
                        listView1.Items[i].Checked = true;
                }
                listView1.Refresh();
            }
            else
                MessageBox.Show(string.Format("加载检测方法配置失败,{0}请检查是否需要配置检测算子", Environment.NewLine), "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        #region 图片管理按钮事件
        private void Save_Btn_Click(object sender, EventArgs e)
        {
            try
            {
                UpdateParam(_selectedpara.InspGroup[tabControl2.SelectedIndex].CameraName);//tabControl2.SelectedTab.Text 
                var order = _tempproduct.ParamList.OrderBy(x => x.PicParameter.Picindex).ToList();
                _tempproduct.ParamList.Clear();
                order.ForEach(x => _tempproduct.ParamList.Add(x));
                ProductManager.SaveProduct(_tempproduct);
                MessageBox.Show("保存成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存失败!\n" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
        }
        private void UpdateParam(string cname)
        {
            var index = _tempproduct.ParamList[picturelist_Rad.SelectedIndex].InspGroup.FindIndex(x => x.CameraName.Equals(cname));
            if (index < -1)
            {
                MessageBox.Show(string.Format("没有找到{0}参数", cname));
                return;
            }
            _tempproduct.ParamList[picturelist_Rad.SelectedIndex].InspGroup[index].InspMethods = new List<int>();
            foreach (ListViewItem s in listView1.CheckedItems)
                _tempproduct.ParamList[picturelist_Rad.SelectedIndex].InspGroup[index].InspMethods.Add(s.ImageIndex);
        }
        private void GreatPic_Btn_Click(object sender, EventArgs e)
        {
            TextInputForm tif = new TextInputForm("请输入图片名称", "创建图片");
            tif.ShowDialog();
            if (tif.IsConform)
            {
                if (picturelist_Rad.Items.Contains(tif.InputString))
                {
                    MessageBox.Show("输入的图片名称已存在,请重新输入!", "新建图片失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                int nextindex = _tempproduct.ParamList.Count();
                _tempproduct.ParamList.Add(new AlgParameter(tif.InputString, nextindex));
                LoadProduct(_tempproduct);
                MessageBox.Show("新建图片成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                _hang = true;
            }
        }
        private void DeletePic_Btn_Click(object sender, EventArgs e)
        {
            int index = Selindex();
            if (index > -1)
            {
                if (MessageBox.Show("是否删除当前选中图片?", "提示", MessageBoxButtons.YesNo) == DialogResult.No)
                    return;
                _tempproduct.ParamList.RemoveAt(index);
                LoadProduct(_tempproduct);
                MessageBox.Show("删除图片成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void Copypic_Btn_Click(object sender, EventArgs e)
        {
            int index = Selindex();
            if (index > -1)
            {
                TextInputForm tif = new TextInputForm("输入图片名称", "复制图片");
                tif.ShowDialog();
                if (tif.IsConform)
                {
                    if (picturelist_Rad.Items.Count > 0 && picturelist_Rad.Items.Contains(tif.InputString))
                    {
                        MessageBox.Show("输入的图片名称已存在,请重新输入!", "复制图片失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    int nextindex = _tempproduct.ParamList.Count();
                    _tempproduct.ParamList.Add(_tempproduct.ParamList[index].clone(tif.InputString, nextindex));
                    LoadProduct(_tempproduct);
                    MessageBox.Show("复制图片成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    _hang = true;
                }
            }
        }
        #endregion 图片管理按钮事件

        private int Selindex()
        {
            if (picturelist_Rad.Items.Count < 1 || picturelist_Rad.SelectedIndex < 0 || _tempproduct.ParamList == null || _tempproduct.ParamList.Count < 1)
                return -1;
            return picturelist_Rad.SelectedIndex;
        }
        private void listView1_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            try
            {
                var index = -1;
                if (_selectedpara == null || _isLoad || tabControl2.TabPages.Count < 1)
                    return;
                if (tabControl2.SelectedIndex < 0)
                    index = 0;
                else
                    index = _selectedpara.InspGroup.FindIndex(x => x.CameraName.Equals(_selectedpara.InspGroup[tabControl2.SelectedIndex].CameraName));
                if (index < -1)
                {
                    MessageBox.Show(string.Format("没有找到{0}参数", tabControl2.SelectedTab.Text));
                    return;
                }
                int type = e.Item.ImageIndex;
                if (e.Item.Checked && !_selectedpara.InspGroup[index].InspMethods.Contains(type))
                {
                    _selectedpara.InspGroup[index].InspMethods.Add(type);
                }
                else if (!e.Item.Checked && _selectedpara.InspGroup[index].InspMethods.Contains(type))
                {
                    _selectedpara.InspGroup[index].InspMethods.Remove(type);
                }
                Rerefrush(2 * (comboBox1.SelectedIndex + 1), index);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error" + ex.Message);
            }
        }

        private void 编辑图片算子ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!编辑图片算子ToolStripMenuItem.Checked)
            {
                if (comboBox1.SelectedIndex > 1)
                    return;
                splitContainer3.Panel2Collapsed = false;
                编辑图片算子ToolStripMenuItem.Checked = true;
                编辑图片算子ToolStripMenuItem.Text = "取消编辑";
            }
            else
            {
                splitContainer3.Panel2Collapsed = true;
                编辑图片算子ToolStripMenuItem.Checked = false;
                编辑图片算子ToolStripMenuItem.Text = "编辑图片算子";
            }
        }

        private void tabControl2_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl2.SelectedIndex < 0)
                return;
            SelectMethod(_selectedpara.InspGroup[tabControl2.SelectedIndex]);
        }

        private void AddBtn_Click(object sender, EventArgs e)
        {
            var source = Device.Parameter.CameraList.Select(x => x.CameraName);
            var list = _selectedpara.InspGroup.Select(x => x.CameraName);
            var item = source.Except(list);
            if (item == null || item.ToList().Count == 0)
            {
                MessageBox.Show("添加失败！当前参数已经包含所有相机参数，请先添加相机后重试！",
                    "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            var ptp = new ParamTabelPage();
            var newparam = new InspGroupParameter(item.ToList().First());
            if ((sender as Button).Name.Contains("Copy"))
            {
                var index = tabControl2.SelectedIndex;
                if (index < 0)
                    return;
                newparam = _selectedpara.InspGroup[index].Clone();
                newparam.CameraName = item.ToList().First();
            }
            _selectedpara.InspGroup.Add(newparam);
            ptp.SetSourcce(newparam);
            tabControl2.TabPages.Add(ptp);
        }

        private void RemoveBtn_Click(object sender, EventArgs e)
        {
            var index = tabControl2.SelectedIndex;
            if (index < 0)
                return;
            if (MessageBox.Show(string.Format ("确定删除 {0}图{1} 的参数?", 
                _selectedpara.PicParameter.Picname, 
                _selectedpara.InspGroup[index].CameraName)
                , "提示", MessageBoxButtons.YesNo,MessageBoxIcon.Question ) == DialogResult.No)
                return;
            _selectedpara.InspGroup.RemoveAt(index);
            tabControl2.TabPages.RemoveAt(index);
        }

        private void CopyBtn_Click(object sender, EventArgs e)
        {
            AddBtn_Click(sender, e);
        }

        private void tabControl2_DrawItem(object sender, DrawItemEventArgs e)
        {
            Rectangle rec1 = tabControl2.GetTabRect(e.Index);
            StringFormat StringF = new StringFormat();
            StringF.Alignment= StringAlignment.Center;
            StringF.LineAlignment = StringAlignment.Center;            SolidBrush cr;
            if (e.Index == tabControl2.SelectedIndex)
                cr = new SolidBrush(Color.DodgerBlue);
            else
                cr = new SolidBrush(Color.White);
            e.Graphics.FillRectangle(cr, rec1);
            e.Graphics.DrawString(tabControl2.Controls[e.Index].Text, new Font("Segoe UI", 8.25f), new SolidBrush(Color.Black), rec1, StringF);
        }
    }
}
